<!DOCTYPE html>












  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">









  
  
    
  
  <link rel="stylesheet" media="all" href="https://cdnjs.cloudflare.com/ajax/libs/Han/3.3.0/han.min.css">




<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">



















  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.3.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.3.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '6.3.0',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="问题在调用一个方法后需要链式的获取某个字段, 比如: 123// 调用接口, 获取用户名ResponseDTO dto = xxxServcice.foo();String username = dto.getUser().getUserName(); 但是上面的方法可能会抛出空指针异常, 因此, 为了程序的健壮性, 我们一般在每一步的get前都需要进行非空判断: 12345678// 调用接口,">
<meta name="keywords" content="jdk">
<meta property="og:type" content="article">
<meta property="og:title" content="java8-optional">
<meta property="og:url" content="http://codertang.com/2019/03/29/jdk8-optional/index.html">
<meta property="og:site_name" content="Tonny&#39;s Blog">
<meta property="og:description" content="问题在调用一个方法后需要链式的获取某个字段, 比如: 123// 调用接口, 获取用户名ResponseDTO dto = xxxServcice.foo();String username = dto.getUser().getUserName(); 但是上面的方法可能会抛出空指针异常, 因此, 为了程序的健壮性, 我们一般在每一步的get前都需要进行非空判断: 12345678// 调用接口,">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2021-02-25T09:25:48.211Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="java8-optional">
<meta name="twitter:description" content="问题在调用一个方法后需要链式的获取某个字段, 比如: 123// 调用接口, 获取用户名ResponseDTO dto = xxxServcice.foo();String username = dto.getUser().getUserName(); 但是上面的方法可能会抛出空指针异常, 因此, 为了程序的健壮性, 我们一般在每一步的get前都需要进行非空判断: 12345678// 调用接口,">






  <link rel="canonical" href="http://codertang.com/2019/03/29/jdk8-optional/">



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>java8-optional | Tonny's Blog</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tonny's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">莫等闲, 白了少年头, 空悲切</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>
  </li>

      
      
    </ul>
  

  
    

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://codertang.com/2019/03/29/jdk8-optional/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tonny Yi">
      <meta itemprop="description" content="Coding, Life, Zen">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tonny's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">java8-optional
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-03-29 09:52:53" itemprop="dateCreated datePublished" datetime="2019-03-29T09:52:53+08:00">2019-03-29</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2021-02-25 17:25:48" itemprop="dateModified" datetime="2021-02-25T17:25:48+08:00">2021-02-25</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/jdk/" itemprop="url" rel="index"><span itemprop="name">jdk</span></a></span>

                
                
                  ，
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/jdk/source/" itemprop="url" rel="index"><span itemprop="name">source</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <h1 id="问题"><a href="#问题" class="headerlink" title="问题"></a>问题</h1><p>在调用一个方法后需要链式的获取某个字段, 比如:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 调用接口, 获取用户名</span></span><br><span class="line">ResponseDTO dto = xxxServcice.foo();</span><br><span class="line">String username = dto.getUser().getUserName();</span><br></pre></td></tr></table></figure>
<p>但是上面的方法可能会抛出空指针异常, 因此, 为了程序的健壮性, 我们一般在每一步的<code>get</code>前都需要进行非空判断:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 调用接口, 获取用户名</span></span><br><span class="line">ResponseDTO dto = xxxServcice.foo();</span><br><span class="line"><span class="keyword">if</span> (dto != <span class="keyword">null</span>) &#123;</span><br><span class="line">    User user = dto.getUser();</span><br><span class="line">    <span class="keyword">if</span> (user != <span class="keyword">null</span>)&#123;</span><br><span class="line">        String username = user.getUserName();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果字段获取链路过深, 那么这些非空判断非常多, 很烦. 下面介绍下 如何使用 jdk8 中的<code>Optional</code>类解决这个问题.</p>
<h1 id="Optional"><a href="#Optional" class="headerlink" title="Optional"></a>Optional</h1><h2 id="API"><a href="#API" class="headerlink" title="API"></a>API</h2><p>首先看一下<code>Optional</code>都有哪些方法</p>
<h3 id="构造类方法"><a href="#构造类方法" class="headerlink" title="构造类方法"></a>构造类方法</h3><p>有三个静态 <code>empty()</code>, <code>ofNullAble()</code> 和 <code>of()</code> 可以创建<code>Optional</code>对象<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 显示的创建一个包含 Null 值的 Optional 对象</span></span><br><span class="line">Optional&lt;String&gt; empty = Optional.empty();</span><br><span class="line"></span><br><span class="line">String username = <span class="keyword">null</span>;</span><br><span class="line"><span class="comment">// 创建一个值可以为空的 Optional 对象</span></span><br><span class="line">Optional&lt;String&gt; nullable = Optional.ofNullable(username);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 创建一个值不能为空的 Optional 对象, 值为空时会抛出空指针异常</span></span><br><span class="line">Optional&lt;String&gt; of = Optional.of(username);</span><br></pre></td></tr></table></figure></p>
<h3 id="判断类方法"><a href="#判断类方法" class="headerlink" title="判断类方法"></a>判断类方法</h3><p>就一个实例方法<code>isPresent()</code>用来判断值是否为<code>null</code><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Optional&lt;String&gt; optional = Optional.of(username);</span><br><span class="line"><span class="comment">// 如果值不为 null(不推荐这种用法, 与原来的非空判断写法没有区别)</span></span><br><span class="line"><span class="keyword">if</span> (optional.isPresent()) &#123;</span><br><span class="line">    <span class="comment">// 获取值</span></span><br><span class="line">    username = optional.get();</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"username cannot null"</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="获取值类方法"><a href="#获取值类方法" class="headerlink" title="获取值类方法"></a>获取值类方法</h3><p>一共有4个方法, <code>get()</code>, <code>orElse(T)</code>, <code>orElseGet(Supplier)</code> 和 <code>orElseThrow(Supplier)</code>, 对应着当值为<code>null</code>时的不同处理策略<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 值为 null 时返回默认值</span></span><br><span class="line">username = optional.orElse(<span class="string">"张三"</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 值为 null 时调用Supplier接口实现来获取值</span></span><br><span class="line">username = optional.orElseGet(() -&gt; &#123;</span><br><span class="line">    <span class="keyword">return</span> yyService.get();</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 值为 null 时直接抛出异常, 该异常对象由Supplier接口实现创建</span></span><br><span class="line">username = optional.orElseThrow(() -&gt; &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"username cannot be null"</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 如果值为 null 抛出默认的NoSuchElementException异常</span></span><br><span class="line">username = of.get();</span><br></pre></td></tr></table></figure></p>
<h3 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 当值不为 null 时消费该值, 接受一个 Consumer 接口实现</span></span><br><span class="line">optional.ifPresent(username -&gt; &#123;</span><br><span class="line">    <span class="comment">// </span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 对值进行过滤, 通过则返回当前 Optional 对象, 否则调用 empty() 返回空值对象</span></span><br><span class="line">optional = optional.filter(StringUtils::isNotBlank);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 该方法会将入参Function接口实现返回值包装成 Optional 对象, 从而实现链式操作</span></span><br><span class="line">Optional&lt;String&gt; s1 = of.map(s -&gt; &#123;</span><br><span class="line">    <span class="keyword">return</span> s + <span class="string">"12"</span>;</span><br><span class="line">&#125;).map(String::toUpperCase);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 类似 map, 但入参Function接口实现的返回值类型是 Optional 对象了</span></span><br><span class="line"><span class="comment">// 且要求该对象不能为 null</span></span><br><span class="line">Optional&lt;String&gt; s1 = of.flatMap(s -&gt; &#123;</span><br><span class="line">    <span class="keyword">return</span> Optional.of(s + <span class="string">"12"</span>);</span><br><span class="line">&#125;).map(String::toUpperCase);</span><br></pre></td></tr></table></figure>
<h2 id="最佳实践"><a href="#最佳实践" class="headerlink" title="最佳实践"></a>最佳实践</h2><p>回到上面的问题, 看看如何使用<code>Optional</code>解决联系空值判断的问题.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">String username = Optional.ofNullable(dto)</span><br><span class="line">        .map(ResponseDTO::getUser)</span><br><span class="line">        .map(User::getUsername)</span><br><span class="line">        .orElseThrow(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> RuntimeException(<span class="string">"username cannot be null"</span>);</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// do something with username</span></span><br></pre></td></tr></table></figure>
<ol>
<li><strong>尽量避免在程序中直接调用<code>Optional</code>对象的<code>get()</code>和<code>isPresent()</code>方法</strong></li>
<li><strong>避免使用<code>Optional</code>类型声明实体类的属性</strong>, <code>Optional</code>是没有继承<code>Serializable</code>接口的, 所以一旦用了, 该属性就没法被序列化的</li>
<li><strong>Optional 主要用作返回类型以构建流畅的API</strong>, <strong>不要使用<code>Optional</code>作为方法的入参</strong>, 这样做会让代码变得复杂. </li>
</ol>
<h2 id="JDK9增强"><a href="#JDK9增强" class="headerlink" title="JDK9增强"></a>JDK9增强</h2><p>上面介绍的 API 都是基于 JDK8 的, JDK 9 为 <code>Optional</code> 类添加了三个方法: <code>or()</code>,<code>ifPresentOrElse()</code> 和 <code>stream()</code>.</p>
<ol>
<li><p><code>or()</code> 方法与 <code>orElse()</code> 和 <code>orElseGet()</code> 类似, 它们都在对象为空的时候提供了替代情况. </p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">User result = Optional.ofNullable(user)</span><br><span class="line">     .or(() -&gt; Optional.of(<span class="keyword">new</span> User(<span class="string">"default"</span>,<span class="string">"1234"</span>)))</span><br><span class="line">     .get();</span><br></pre></td></tr></table></figure>
</li>
<li><p><code>ifPresentOrElse()</code> 方法需要两个参数: 一个 <code>Consumer</code> 和一个 <code>Runnable</code>. 如果对象包含值, 会执行 <code>Consumer</code> 的动作, 否则运行 Runnable.</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Optional.ofNullable(user)</span><br><span class="line">    .ifPresentOrElse(</span><br><span class="line">        u -&gt; logger.info(<span class="string">"User is:"</span> + u.getEmail()), </span><br><span class="line">        () -&gt; logger.info(<span class="string">"User not found"</span>)</span><br><span class="line">    );</span><br></pre></td></tr></table></figure>
</li>
<li><p><code>stream()</code> 方法把<code>Optional</code>实例转换为 <code>Stream</code> 对象, 从而可以使用大量的<code>Stream</code>接口</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; emails = Optional.ofNullable(user)</span><br><span class="line">  .stream()</span><br><span class="line">  .filter(u -&gt; u.getEmail() != <span class="keyword">null</span> &amp;&amp; u.getEmail().contains(<span class="string">"@"</span>))</span><br><span class="line">  .map(u -&gt; u.getEmail())</span><br><span class="line">  .collect(Collectors.toList());</span><br></pre></td></tr></table></figure>
</li>
</ol>

      
    </div>

    

    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Tonny Yi</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://codertang.com/2019/03/29/jdk8-optional/" title="java8-optional">http://codertang.com/2019/03/29/jdk8-optional/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc/4.0/" rel="external nofollow" target="_blank">CC BY-NC 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/jdk/" rel="tag"># jdk</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/02/26/spring-resource/" rel="next" title="spring-resource">
                <i class="fa fa-chevron-left"></i> spring-resource
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/04/11/code-snippet/" rel="prev" title="code-snippet">
                code-snippet <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.png" alt="Tonny Yi">
            
              <p class="site-author-name" itemprop="name">Tonny Yi</p>
              <p class="site-description motion-element" itemprop="description">Coding, Life, Zen</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">49</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">42</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">59</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/tonnyyi" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:tonnyemails@gmail.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
            </div>
          

          
          
            <div class="cc-license motion-element" itemprop="license">
              <a href="https://creativecommons.org/licenses/by-nc/4.0/" class="cc-opacity" target="_blank">
                <img src="/images/cc-by-nc.svg" alt="Creative Commons">
              </a>
            </div>
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#问题"><span class="nav-number">1.</span> <span class="nav-text">问题</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Optional"><span class="nav-number">2.</span> <span class="nav-text">Optional</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#API"><span class="nav-number">2.1.</span> <span class="nav-text">API</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#构造类方法"><span class="nav-number">2.1.1.</span> <span class="nav-text">构造类方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#判断类方法"><span class="nav-number">2.1.2.</span> <span class="nav-text">判断类方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#获取值类方法"><span class="nav-number">2.1.3.</span> <span class="nav-text">获取值类方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#其他"><span class="nav-number">2.1.4.</span> <span class="nav-text">其他</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#最佳实践"><span class="nav-number">2.2.</span> <span class="nav-text">最佳实践</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JDK9增强"><span class="nav-number">2.3.</span> <span class="nav-text">JDK9增强</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tonny Yi</span>

  

  
</div>


  <script src="https://unpkg.com/mermaid@7.1.2/dist/mermaid.min.js"></script>
  <script>
    if (window.mermaid) {
      mermaid.initialize("");
    }
  </script>





  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://theme-next.org">NexT.Mist</a></div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.3.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.3.0"></script>



  



	





  





  










  





  

  

  

  

  
  

  

  

  

  

  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
    }

    .highlight-wrap:hover .copy-btn,
    .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  <script>
    $('.highlight').each(function (i, e) {
      var $wrap = $('<div>').addClass('highlight-wrap')
      $(e).after($wrap)
      $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function (e) {
        var code = $(this).parent().find('.code').find('.line').map(function (i, e) {
          return $(e).text()
        }).toArray().join('\n')
        var ta = document.createElement('textarea')
        document.body.appendChild(ta)
        ta.style.position = 'absolute'
        ta.style.top = '0px'
        ta.style.left = '0px'
        ta.value = code
        ta.select()
        ta.focus()
        var result = document.execCommand('copy')
        document.body.removeChild(ta)
        
          if(result)$(this).text('复制成功')
          else $(this).text('复制失败')
        
        $(this).blur()
      })).on('mouseleave', function (e) {
        var $b = $(this).find('.copy-btn')
        setTimeout(function () {
          $b.text('复制')
        }, 300)
      }).append(e)
    })
  </script>


</body>
</html>
